package org.vt.ece4564.pcw.assignment2;

import java.io.IOException;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import javax.servlet.ServletConfig;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.vt.ece4564.pcw.assignment2data.MessageFromAndroid;

@SuppressWarnings("serial")
public class TextInClassPostMessagesAndroid extends HttpServlet {
	
	@Override
	public void init(ServletConfig servletConfig) {
		
	}
	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		response.setContentType("text/plain");
		
		List<Cookie> cookies = Arrays.asList(request.getCookies());
		String username = "";
		
		for (Cookie c : cookies) {
			String name = c.getName();
			String value = c.getValue();
			
			if (name.equals("loggedIn")) {
				String[] values = value.split(":");
				if (values.length != 3) {
					response.getWriter().write("Error: Invalid Cookie");
					return;
				}
				Date currentDate = new Date();
				long cookieExpiration = Long.valueOf(values[1]).longValue();
				
				if (currentDate.getTime() > cookieExpiration) {
					response.getWriter().write("Error: Expired Cookie");
					return;
				}
				
				username = values[0];
				break;
			}
		}
		
		if (username.equals("")) {
			response.getWriter().write("Error: Invalid Cookie");
			return;
		}
		
		String fromNumber = request.getParameter("from_number");
		List<String> messages = Arrays.asList(request.getParameterValues("message"));
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		for (String message : messages) {
			pm.makePersistent(new MessageFromAndroid(username, message, fromNumber));
		}
		
		response.getWriter().write("Success");
		
	}
	
}
